﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Intorise.Net;
using System.Drawing;
using Intorise.Common;
using System.Net;
using System.Threading;
using Config;
using System.Collections;

namespace Model
{
    public partial class Player
    {
        public byte[] Version { get; set; }
        public long ID { get; set; }
        public Account PlayerAccount { get; set; }
        public ProfessionEnum Profession { get; set; }
        public string AccountName { get; set; }
        public string ServerID { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public Map CurrentMap { get; set; }
        public int CurrentHP { get; set; }
        public int CurrentMP { get; set; }
        public int TotalHP { get; set; }
        public int TotalMP { get; set; }
        public int TotalGold { get; set; }
        public bool IsRide { get; set; }
        public short X { get; set; }
        public short Y { get; set; }
        public bool AutoFight { get; set; }
        public bool PauseAutoFight { get; private set; }
        public bool Entered { get; set; }
        public int Line { get; set; }
        public long Exp { get; set; }
        public double ExpRange { get; set; }
        public List<Thing> Items = new List<Thing>();
        public List<Medicinal> medicinals = new List<Medicinal>();
        public List<Item> things = new List<Item>();
        public List<string> needGetTiems = new List<string>();
        public List<string> dontPickupTiems = new List<string>();
        public List<string> sellExcepet = new List<string>();

        public PlayerStatusEnum Status
        {
            get
            {
                lock (statusLocker) { return status; }
            }
            set
            {
                lock (statusLocker) { status = value; }
            }
        }
        /// <summary>
        /// 当前坐标
        /// </summary>
        public Point Location { get; set; }
        public Point FightLocation { get; set; }
        /// <summary>
        /// 挂机地图和走路路线
        /// </summary>
        public FightLocation FightMapLocation { get; set; }
        public Point MoveToPoint { get; set; }
        public int KilledCount { get; private set; }
        public int DeadCount { get; private set; }
        public int LoginCount { get; private set; }
        public string ItemInfo { get; private set; }
        public bool Initialized { get; set; }

        public BotConfig Config { get; private set; }

        object statusLocker = new object();
        PlayerStatusEnum status;
        BotEngine engine = null;
        NetTools net = new NetTools();
        Thread thread = null;
        Thread checkAutoFightThread = null;
        int lastKilledCount = 0;
        int reAutoFightCount = 0;
        bool logServerInfo = false;
        bool logDebugInfo = false;
        bool gameEntered = false;
        int reconnectCount = 0;
        DateTime startAutoFightTime = DateTime.Now;
        List<Medicinal> lastBuyMedicinals = new List<Medicinal>();
        public static Player Master = null;
        static List<Player> queue = new List<Player>();//需要交易的玩家队列

        #region AutoResetEvent
        object treatLocker = new object();
        object takeMedicinalLocker = new object();
        object pickupLocker = new object();
        #endregion

        #region timeout define
        DateTime lastTakMPMedicinalTime = DateTime.MinValue;
        DateTime lastTakHPMedicinalTime = DateTime.MinValue;
        #endregion

        List<Skill> skillList = new List<Skill>();
        Skill skill = Skills.GetSkill("穿透箭");

        public Player(Account account, BotConfig config)
        {
            PlayerAccount = account;
            var text = PlayerAccount.Username.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            if (text.Length == 2)
            {
                PlayerAccount.Platform = text[0].ToLower();
                PlayerAccount.Username = text[1];
            }
            else
            {
                PlayerAccount.Platform = "";
            }
            AccountName = PlayerAccount.Username;
            ServerID = PlayerAccount.ServerID;
            PauseAutoFight = false;
            Status = PlayerStatusEnum.等待;
            CurrentHP = 100;
            CurrentMP = 100;
            TotalHP = 100;
            TotalMP = 100;
            this.Config = config;
            switch (PlayerAccount.Platform)
            {
                case "qd":
                    engine = new QdBotEngine(this);
                    break;
                case "yy":
                    engine = new YyBotEngine(this);
                    break;
                case "gm":
                    engine = new GmBotEngine(this);
                    break;
                default:
                    engine = new BotEngine(this);
                    break;
            }

            RefreshConfig();
        }

        public void RefreshConfig()
        {
            needGetTiems.Clear();
            if (Config.NeedPickupItems != null)
            {
                needGetTiems.AddRange(Config.NeedPickupItems.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            this.dontPickupTiems.Clear();
            if (Config.DontPickupItems != null)
            {
                dontPickupTiems.AddRange(Config.DontPickupItems.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            sellExcepet.Clear();
            if (Config.SellExcepet != null)
            {
                sellExcepet.AddRange(Config.SellExcepet.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            logServerInfo = ((MainConfig)ConfigManager.ApplicationConfig).LogServerInfo;
            logDebugInfo = ((MainConfig)ConfigManager.ApplicationConfig).LogDebugInfo;
        }

        public bool Login()
        {
            Entered = false;
            LoginCount++;
            this.Status = PlayerStatusEnum.登录中;
            bool result = false;
            try
            {
                result = engine.Login();
                if (result)
                {
                    this.Status = PlayerStatusEnum.已登录;
                    ConsoleBLL.WriteLineInfo(this.ToString() + " 登录成功");
                    result = engine.EnterGameServer();
                    if (result)
                    {
                        gameEntered = true;
                        this.Status = PlayerStatusEnum.已进入游戏;
                        ConsoleBLL.WriteLineInfo(this.ToString() + " 进入游戏成功");
                        InitSkills();
                    }
                    else
                    {
                        gameEntered = false;
                        this.Status = PlayerStatusEnum.等待;
                        ConsoleBLL.WriteLineInfo(this.ToString() + " 进入游戏失败");
                    }
                }
                else
                {
                    if (LoginCount > Config.MaxLoginCount)
                    {
                        this.Status = PlayerStatusEnum.停止;
                    }
                    else if (this.Status != PlayerStatusEnum.账户密码错误)
                    {
                        this.Status = PlayerStatusEnum.等待;
                    }
                    ConsoleBLL.WriteLineInfo(this.ToString() + " 登录失败");
                }
                return result;
            }
            catch (Exception ex)
            {
                ConsoleBLL.WriteLineError("登录出错：\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                this.Status = PlayerStatusEnum.等待;
                return false;
            }
        }

        private void InitSkills()
        {
            skillList.Clear();
            switch (Profession)
            {
                case ProfessionEnum.剑士:
                    skillList.Add(Skills.GetSkill("霹雳回旋斩"));
                    skillList.Add(Skills.GetSkill("霹雳地裂斩"));
                    break;
                default:
                    //skillList.Add(Skills.GetSkill("黑龙波"));
                    //skillList.Add(Skills.GetSkill("地狱火"));
                    skillList.Add(Skills.GetSkill("穿透箭"));
                    break;
            }
        }

        /// <summary>
        /// 进入地图
        /// </summary>
        public void EnterMap()
        {
            //ConsoleBLL.WriteLine("进入地图");
            var command = Commands.GetCommand("进入地图");
            engine.SendData(command.Data);
        }

        /// <summary>
        /// 传送
        /// </summary>
        /// <param name="map"></param>
        public bool Transmit(Map map)
        {
            //ConsoleBLL.WriteLineInfo("传送到：" + map.Name);

            DateTime begin = DateTime.Now;
            var data = DataPackager.GetTransmitData(map);
            engine.SendData(data);
            EnterMap();

            while (true)
            {
                Thread.Sleep(100);

                if (this.CurrentMap != null && this.CurrentMap.Name == map.Name)
                {
                    return true;
                }
                DateTime end = DateTime.Now;
                var span = end - begin;
                if (span.TotalSeconds > Config.TimeoutMove)
                {
                    break;
                }
            }

            //ConsoleBLL.WriteLineWaring("传送超时");
            return false;
        }

        public void ReAutoFight()
        {
            GameHelper.RunThreadPool(() =>
            {
                Transmit(Maps.GetMap("勇者大陆"));
                Thread.Sleep(1000);
                Quit();
            });
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="target">目的地址坐标</param>
        public bool GoTo(Point target)
        {
            return GoTo(target.X, target.Y);
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public bool GoTo(int x, int y, bool ride = true)
        {
            if (ride && !IsRide)
            {
                Ride();
            }
            MoveToPoint = new Point(x, y);
            var data = DataPackager.GetWalkData(X, Y, new Point(x, y), 6);
            //ConsoleBLL.WriteLine("移动到：" + x + "，" + y);
            engine.SendData(data);

            DateTime begin = DateTime.Now;
            while (true)
            {
                Thread.Sleep(100);
                if (this.Location == MoveToPoint)
                {
                    Location = MoveToPoint;
                    return true;
                }
                DateTime end = DateTime.Now;
                var span = end - begin;
                if (span.TotalSeconds > Config.TimeoutMove)
                {
                    break;
                }
            }

            //ConsoleBLL.WriteLineError("移动超时");
            return false;
        }

        public bool GoTo(List<Point> points)
        {
            bool success = true;
            points.ForEach(x =>
            {
                success = success && GoTo(x);
                if (!success) { return; }
            });
            return success;
        }

        /// <summary>
        /// 开始玩
        /// </summary>
        public void Play()
        {
            this.Location = Point.Empty;
            Status = PlayerStatusEnum.开始挂机;
            int line = this.Line;
            ConsoleBLL.WriteLineInfo(this.ToString() + " auto fight begin.");
            thread = Thread.CurrentThread;
            InitProcessor();
            Thread.Sleep(2000);
            #region 换线
            if (Config.RandomLine)
            {
                Change(new Random(new Random((int)DateTime.Now.Ticks).Next()).Next(10) + 1);
            }
            else if (line > 0)
            {
                Change(line);
            }
            else
            {
                Change(Config.LineNumber);
            }

            #endregion
            Thread.Sleep(1000);
            Ride();
            #region 签到及领取奖励
            StartSigninTimer();
            #endregion

            if (this.ID == Player.Master.ID)
            {
                StartTradeTimer();//启动交易线程
            }
            //BuyMedicine(Thing.GetThing(Thing.MedicinalType.MP0));
            //return;
            if (AutoFight)
            {
                if (GoFightLocation())
                {
                    //Treat(Thing.MedicinalType.HP2);
                    StartAutoFight();
                }
                else
                {
                    //ConsoleBLL.WriteLineError("移动到挂机地点失败！");
                    Quit();
                }
            }
            ConsoleBLL.WriteLineInfo(this.ToString() + " auto fight end.");
            Status = PlayerStatusEnum.已进入游戏;
        }

        public void CreateCharacter()
        {
            if (engine.Login())
            {
                engine.CreateCharacter();
            }
        }

        public void Pause()
        {
            this.PauseAutoFight = true;
            this.Status = PlayerStatusEnum.已登录;
        }

        public void Continue()
        {
            this.PauseAutoFight = false;
            this.Status = PlayerStatusEnum.自动打怪;
        }

        protected bool GoFightLocation()
        {
            this.Status = PlayerStatusEnum.前往挂机地点;
            DateTime begin = DateTime.Now;
            while (this.Location == Point.Empty)
            {
                DateTime end = DateTime.Now;
                var span = end - begin;
                if (span.TotalSeconds > Config.TimeoutMove)
                {
                    break;
                }

                Transmit(Maps.GetMap(FightMapLocation.MapName, this.PlayerAccount.Platform));
                Thread.Sleep(1000);
            }

            if (Location == Point.Empty)
            {
                ConsoleBLL.WriteLineError("获取当前坐标失败！");
                return false;
            }

            if (FightMapLocation == null)
            {
                ConsoleBLL.WriteLineError(string.Format("{0}:{1}未设定挂机地点！将在当前地点开始挂机", AccountName, ServerID));
                FightLocation = Location;
                return true;
            }

            if (CurrentMap != null && CurrentMap.Name == FightMapLocation.MapName)
            {
                if (GameHelper.GetDistance(Location, FightLocation) < 20)
                {
                    if (GoTo(FightLocation)) { return true; }
                }
            }

            var map = Maps.GetMap(FightMapLocation.MapName);
            if (map == null)
            {
                return false;
            }
            if (!Transmit(map)) { return false; };
            EnterMap();
            foreach (Point p in FightMapLocation.LocationPoints)
            {
                int count = 1;
                while (count < 4)
                {
                    if (GoTo(p))
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    ConsoleBLL.WriteLineError(string.Format("移动到{0}失败，重试第{1}次！", p, count));
                    count++;
                }
                if (count == 4)
                {
                    return false;
                }
            }

            ConsoleBLL.WriteLine("已到达挂机地点");
            return true;
        }

        public bool UseItem(Thing item)
        {
            engine.SendData(DataPackager.GetUseItemData(this, item)); return true;
        }

        public bool EquipItem(Thing item)
        {
            engine.SendData(DataPackager.GetEquipItemData(item)); return true;
        }

        public bool ReceiveRegisterItem()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x09, 0x28, 0x28, 0x00, 0x00, 0x00, 0x01 });
            return true;
        }

        public bool ReceiveRegisterItem(byte count)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x52, 0x8B }, count);
            engine.SendData(data);
            return true;
        }

        public bool TiLian(Thing thing)
        {
            ConsoleBLL.WriteLineInfo(this + " 神器提炼");
            engine.SendData(DataPackager.GetTiLianData(thing)); return true;
        }

        public bool TakeMedicine(Medicinal medicinal)
        {
            lock (takeMedicinalLocker)
            {

                DateTime lastTime;
                if (medicinal.Name.Contains("治疗"))
                {
                    lastTime = lastTakHPMedicinalTime;
                }
                else
                {
                    lastTime = lastTakMPMedicinalTime;
                }
                DateTime now = DateTime.Now;
                if ((now - lastTime).TotalSeconds < medicinal.CD)
                {
                    ConsoleBLL.WriteInfo("CD没到");
                    return false;
                }
                if (logDebugInfo)
                {
                    ConsoleBLL.WriteLineInfo("吃" + medicinal.Name);
                }
                engine.SendData(DataPackager.GetUseItemData(this, medicinal));

                if (medicinal.Name.Contains("治疗"))
                {
                    lastTakHPMedicinalTime = DateTime.Now;
                }
                else
                {
                    lastTakMPMedicinalTime = DateTime.Now;
                }
                lock (medicinals)
                {
                    medicinals.Remove(medicinal);
                }
            }
            return true;
        }

        public bool BuyMedicine(Medicinal medicinal, int count = 1)
        {
            lock (lastBuyMedicinals)
            {
                var item = lastBuyMedicinals.FirstOrDefault(w => w.Name == medicinal.Name);
                if (item != null)
                {
                    if ((DateTime.Now - item.CreateDate).TotalSeconds > 10)
                    {
                        //ConsoleBLL.WriteLineWaring("上次购买的物品已超过10秒还未完成，移除待购买物品！");
                        lastBuyMedicinals.Remove(item);
                    }
                    else
                    {
                        //ConsoleBLL.WriteLineInfo("上次购买还未完成");
                    }
                    return true;
                }
                else
                {
                    lastBuyMedicinals.Add(medicinal);
                }
            }
            //ConsoleBLL.WriteInfo("购买" + medicinal.Name + "x" + count);
            engine.SendData(DataPackager.GetBuyMedicinalData(medicinal, count));
            return true;
        }

        public bool GetItem(ItemDropedMsg item)
        {
            lock (pickupLocker)
            {
                PauseAutoFight = true;
                if (logDebugInfo)
                {
                    ConsoleBLL.WriteLine(string.Format(this + " 拾取物品{0}({1}/{2})", item.DropedItem.Name, item.X / 25, item.Y / 25));
                }
                var sourcePoint = Location;
                var distance = GameHelper.GetDistance(Location, new Point(item.X / 25, item.Y / 25));
                if (distance > Config.GetItemDistance)
                {
                    GoTo(item.X / 25, item.Y / 25, true);
                }
                Thread.Sleep(50);
                engine.SendData(DataPackager.GetItemData(this, item.DropedItem));
                //Thread.Sleep(10);
                //engine.SendData(DataPackager.GetItemData(item.DropedItem));
                GoTo(sourcePoint);
                PauseAutoFight = false;
            }
            return true;
        }

        /// <summary>
        /// 治疗
        /// </summary>
        /// <param name="type"></param>
        public void Treat(Thing.MedicinalType type)
        {
            GameHelper.RunThreadPool(() =>
            {
                Medicinal medicinal = null;
                lock (medicinals)
                {
                    medicinal = medicinals.FirstOrDefault(w => w.Type == (int)type);
                }
                if (medicinal == null)
                {
                    medicinal = Thing.GetThing(type);
                    BuyMedicine(medicinal, 1);
                }
                else
                {
                    TakeMedicine(medicinal);
                }
            });
        }

        public void StartAutoFight()
        {
            checkAutoFightThread = GameHelper.Start(CheckAutoFight);
            this.Status = PlayerStatusEnum.自动打怪;
            ConsoleBLL.WriteLineInfo(this.ToString() + " 开始自动打怪.");
            if (IsRide)
            {
                Ride();
            }


            startAutoFightTime = DateTime.Now;
            Exp = 0;
            ExpRange = 0;
            Random random = new Random();
            long count = 1;
            while (AutoFight)
            {
                if (PauseAutoFight)
                {
                    Thread.Sleep(100); continue;
                }

                if (IsRide)
                {
                    Ride();
                }

                foreach (Skill skill in skillList)
                {
                    if (skill.IsFixedCD)
                    {
                        if ((DateTime.Now - skill.LastUseTime).TotalSeconds < skill.CD) { continue; }
                    }
                    else
                    {
                        if ((DateTime.Now - skill.LastUseTime).TotalSeconds < skill.CD * Config.HLBCD) { continue; }
                    }
                    List<Monster> monsters = new List<Monster>(6);
                    if (skill.IsMultiple)
                    {
                        monsters.AddRange(engine.GetNearestMonster());
                    }
                    else
                    {
                        var monster = engine.GetOneNearestMonster();
                        if (monster != null)
                        {
                            monsters.Add(monster);
                        }
                    }
                    if (monsters.Count > 0)
                    {
                        KillMonster(skill, monsters);
                    }
                    else
                    {
                        if (logDebugInfo) { ConsoleBLL.WriteLine(this + " 没有找到怪物."); }
                        Thread.Sleep(500);
                    }
                    //Thread.Sleep(50);
                }
                if (GameHelper.GetDistance(Location, FightLocation) > 10)
                {
                    //ConsoleBLL.WriteLineInfo("回到指定的挂机坐标");
                    GoTo(FightLocation);
                }
                Thread.Sleep(50);
            }
            try
            {
                checkAutoFightThread.Abort();
            }
            catch (Exception ex) { }
            ConsoleBLL.WriteLineInfo(this.ToString() + " 结束自动打怪.");
        }

        public bool KillMonster(Skill skill, List<Monster> monsters)
        {
            //if (GameHelper.GetDistance(this.Location, monsters.First().Location) > skill.AttackRange)
            //{
            //    GoTo(monsters.First().Location);
            //}
            byte[] data = null;
            data = DataPackager.GetAttactData(this, monsters.ToList(), skill);
            skill.LastUseTime = DateTime.Now;
            //ConsoleBLL.WriteLine(this + string.Format(" 使用{0}攻击{1}个怪物.", skill.Name, monsters.Count));
            engine.SendData(data);
            return true;
        }

        public bool KillMonster(Skill skill, Monster monster)
        {
            List<Monster> list = new List<Monster>(1);
            list.Add(monster);
            return KillMonster(skill, list);
        }

        public bool Ride()
        {
            IsRide = !IsRide;
            engine.SendData(DataPackager.GetRideData());
            return true;
        }

        public bool Sell(Thing item)
        {
            if (logDebugInfo)
            {
                ConsoleBLL.WriteLineInfo("出售" + item.Name);
            }
            engine.SendData(DataPackager.GetSellData(this, item));
            return true;
        }

        public void Signin()
        {
            GameHelper.RunThreadPool(new Action(() =>
            {
                while (true)
                {
                    var command = Commands.GetCommand("签到");
                    ConsoleBLL.WriteLine("签到");
                    engine.SendData(command.Data);
                    Thread.Sleep(24 * 60 * 60 * 1000);
                }
            }));
        }

        public void Change(int line)
        {
            if (logDebugInfo)
            {
                ConsoleBLL.WriteLine(this + " 选线" + line);
            }
            this.Line = line;
            engine.SendData(DataPackager.GetChangeLine(line));
            Thread.Sleep(100);
            EnterMap();
        }

        /// <summary>
        /// 加血
        /// </summary>
        /// <param name="hp"></param>
        public void TreatHP(int hp)
        {
            this.CurrentHP = hp;
            if (TotalHP < CurrentHP) { TotalHP = CurrentHP; }

            if (CurrentHP == 0)
            {
                ConsoleBLL.WriteLineError(this.ToString() + " 死亡，重新开始挂机...");
                //CurrentHP = TotalHP;
                DeadCount++;
                GameHelper.RunThread(ReFight);
                return;
            }
            if (this.CurrentHP >= TotalHP)
            {
                return;
            }
            if (TotalHP - this.CurrentHP >= Config.HP2)
            {
                Treat(Thing.MedicinalType.HP2);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP1)
            {
                Treat(Thing.MedicinalType.HP1);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP0)
            {
                Treat(Thing.MedicinalType.HP0);
            }
        }

        /// <summary>
        /// 复活
        /// </summary>
        public void Revive()
        {
            //ConsoleBLL.WriteLineInfo(this.ToString() + " 进入地图");
            var datas = DataPackager.GetRevive();
            datas.ForEach(x =>
            {
                engine.SendData(x);
                Thread.Sleep(100);
            });
        }

        public void Disconnect()
        {
            this.Status = PlayerStatusEnum.已断线;
            this.AutoFight = false;
        }
        
        public void Quit()
        {
            this.AutoFight = false;
            this.Status = PlayerStatusEnum.等待;

            while (true)
            {
                try
                {
                    if (checkAutoFightThread != null)
                    {
                        checkAutoFightThread.Abort();
                    }
                }
                catch (Exception ex) { }
                if (checkAutoFightThread == null || checkAutoFightThread.ThreadState == ThreadState.Aborted || checkAutoFightThread.ThreadState == ThreadState.Stopped)
                {
                    break;
                }
                Thread.Sleep(100);
            }
            ConsoleBLL.WriteLineInfo(this.ToString() + " 卡机检测线程已经结束");
            while (true)
            {
                try
                {
                    if (thread != null)
                    {
                        thread.Abort();
                    }
                }
                catch (Exception ex) { }
                if (thread == null || thread.ThreadState == ThreadState.Aborted || thread.ThreadState == ThreadState.Stopped)
                {
                    break;
                }
                Thread.Sleep(100);
            }
            ConsoleBLL.WriteLineInfo(this.ToString() + " 自动挂机线程已经结束");
            engine.Stop();
        }

        public override string ToString()
        {
            return AccountName + " " + ServerID + " " + Name;
        }

        private void SumItems(List<IGrouping<string, Thing>> list)
        {
            StringBuilder sb = new StringBuilder();
            list.ForEach(e =>
            {
                sb.Append(e.FirstOrDefault().Name + "(" + e.Count() + ") ");
            });
            this.ItemInfo = sb.ToString();
        }

        private bool IsNeedSell(string name)
        {
            foreach (string s in sellExcepet)
            {
                if (name.Contains(s)) { return false; }
            }
            return true;
        }

        protected void CheckAutoFight(object obj)
        {
            try
            {
                ConsoleBLL.WriteLineInfo(this.ToString() + " 开始卡机检测.");
                while (AutoFight)
                {
                    Thread.Sleep(1000 * Config.TimeoutKilledCount);
                    if (lastKilledCount == KilledCount)
                    {
                        ConsoleBLL.WriteLineWaring(this.ToString() + " " + Config.TimeoutKilledCount + "秒内杀怪数没有变化，重新开始挂机程序！");
                        EnterMap();
                        GameHelper.RunThread(ReFight); break;
                    }
                    else
                    {
                        lastKilledCount = KilledCount;
                    }
                }
                ConsoleBLL.WriteLineInfo(this.ToString() + " 结束卡机检测.");
            }
            catch (Exception ex)
            {
                GameHelper.Handle(ex);
            }
        }

        protected void ReFight()
        {
            this.AutoFight = false;
            if (CurrentHP == 0)
            {
                Status = PlayerStatusEnum.死亡;
                Thread.Sleep(5000);
                Revive();
            }
            else
            {
                Status = PlayerStatusEnum.重新开始挂机;
            }
            while (true)
            {
                try
                {
                    checkAutoFightThread.Abort();
                }
                catch (Exception ex) { }
                if (checkAutoFightThread.ThreadState == ThreadState.Aborted || checkAutoFightThread.ThreadState == ThreadState.Stopped)
                {
                    break;
                }
                Thread.Sleep(100);
            }
            ConsoleBLL.WriteLineWaring(this.ToString() + " 卡机检测线程已经结束");
            while (true)
            {
                try
                {
                    thread.Abort();
                }
                catch (Exception ex) { }
                if (thread.ThreadState == ThreadState.Aborted || thread.ThreadState == ThreadState.Stopped)
                {
                    break;
                }
                Thread.Sleep(100);
            }
            ConsoleBLL.WriteLineWaring(this.ToString() + " 自动挂机线程已经结束");
            this.AutoFight = true;
            if (reAutoFightCount > 2)
            {
                reAutoFightCount = 0;
                this.Quit();
            }
            else
            {
                reAutoFightCount++;
                GameHelper.RunThread(this.Play);
            }
        }

        protected void Trade()
        {

        }
    }
}
